package rapier.sso.server.handler.impl;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import rapier.sso.common.utils.SpringContextUtils;
import rapier.sso.core.config.redis.RedisClient;
import rapier.sso.server.constant.RapierServerConstant;
import rapier.sso.server.handler.IAuthHandler;
import rapier.sso.server.model.Credential;

@Component
public class CaptchaAuthHandler implements IAuthHandler {

	@Autowired
	private RedisClient redisClient;

	@Override
	public boolean support(Credential credential) {
		HttpServletRequest req = SpringContextUtils.getHttpServletRequest();
		return req.getParameterMap().containsKey("captchaVal") && req.getParameterMap().containsKey("captchaKey");
	}

	@Override
	public boolean auth(Credential credential) {
		HttpServletRequest req = SpringContextUtils.getHttpServletRequest();
		String captchaVal = req.getParameter("captchaVal");
		String captchaKey = req.getParameter("captchaKey");
		Object redisCaptcha = redisClient.get(RapierServerConstant.REDIS_SSO_USER_CAPTCHA_KEY + captchaKey);
		// 判断验证码
		if (redisCaptcha == null || !redisCaptcha.toString().equals(captchaVal.trim())) {
			credential.setError("验证码错误!");
			return false;
		}
		return true;
	}

	@Override
	public void release(Credential credential) {
		HttpServletRequest req = SpringContextUtils.getHttpServletRequest();
		String captchaKey = req.getParameter("captchaKey");
		redisClient.remove(RapierServerConstant.REDIS_SSO_USER_CAPTCHA_KEY + captchaKey);
	}
}
